<template>
  <el-form :model="form" label-position="top">
    <el-row>
      <el-col :span="24">
        <el-form-item label="公司名称">
          <el-autocomplete
              v-model="form.companyName"
              :fetch-suggestions="queryCompanies"
              placeholder="请输入公司名称"
              clearable
              class="form-input"
              :trigger-on-focus="true"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="查询深度">
          <el-slider
              v-model="form.depth"
              :min="1"
              :max="5"
              :step="1"
              :marks="{1:'1', 2:'2', 3:'3', 4:'4', 5:'5'}"
              class="form-slider"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" style="text-align: center; margin-top: 16px;">
        <el-button type="primary" @click="handleQuery" class="query-button">
          <el-icon><Search /></el-icon> 查询
        </el-button>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import { ref, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { searchCompanies } from '@/api/company';

export default {
  name: 'SupplyChainForm',
  components: {
    Search
  },
  emits: ['query'],
  setup(props, { emit }) {
    const form = reactive({
      companyName: '',
      depth: 2
    });

    const queryCompanies = async (queryString, callback) => {
      try {
        const response = await searchCompanies({
          keyword: queryString || ''
        });
        
        const companies = Array.isArray(response) ? response : [];
        const suggestions = companies.map(item => ({
          value: item.name || '',
          label: item.name || '',
          ...item
        }));
        
        callback(suggestions);
      } catch (error) {
        console.error('搜索公司失败:', error);
        ElMessage.error('搜索公司失败，请稍后重试');
        callback([]);
      }
    };

    const handleQuery = () => {
      emit('query', {
        companyName: form.companyName.trim(),
        depth: form.depth
      });
    };

    return {
      form,
      queryCompanies,
      handleQuery
    };
  }
};
</script>

<style scoped>
.form-input {
  width: 100%;
  margin-bottom: 5px;
}

.form-slider {
  margin-top: 8px;
  height: 34px;
  width: 100%;
  max-width: 600px;
}

.query-button {
  min-width: 120px;
  padding: 10px 24px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
  border-radius: 6px;
}
</style> 